package utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Util {
	    //加密 
	    public static String getBASE64(String s) {   
		if (s == null) return null;   
		return (new sun.misc.BASE64Encoder()).encode( s.getBytes() );   
		}   
		  
		// 将 BASE64 编码的字符串 s 进行解码   
		public static String getFromBASE64(String s) {   
		if (s == null) return null;   
		sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();   
		try {   
		byte[] b = decoder.decodeBuffer(s);   
		return new String(b);   
		} catch (Exception e) {   
		return null;   
		}   
		}  
	/**
	 * 用MD5算法进行加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @return MD5加密后的结果
	 */

	public static String encodeMD5String(String str) {
		return encode(str, "MD5");
	}

	/**
	 * 用SHA算法进行加密
	 * 
	 * @param str
	 *            需要加密的字符串
	 * @return SHA加密后的结果
	 */

	public static String encodeSHAString(String str) {
		return encode(str, "SHA");
	}
	
	private static String encode(String str, String method) {
		MessageDigest md = null;
		String dstr = null;
		try {
			md = MessageDigest.getInstance(method);
			md.update(str.getBytes());
			dstr = new BigInteger(1, md.digest()).toString(16);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return dstr;
	}
}